<!-- 账单 -->
<template>
  <div class="h-full w-full">
    <div class="py-2 flex gap-8 items-center">
      <span class="text-lg">支出明细</span>
      <el-button type="success" :icon="Plus" @click="openDialog('add')">新增</el-button>
    </div>

    <BasicTable
      :table-data="tableData"
      :columns="columns"
      :operation="true"
      @update:current-row="currentRowChange"
    >
      <template #operate="slotProps">
        <el-button
          type="primary"
          :icon="Edit"
          size="small"
          @click="openDialog('edit', slotProps.scopeData.row)"
        >
          编辑
        </el-button>
        <el-popconfirm
          confirm-button-text="确定"
          cancel-button-text="取消"
          title="确认删除？"
          @confirm="deleteBill(slotProps.scopeData.row)"
        >
          <template #reference>
            <el-button type="danger" :icon="Delete" size="small"> 删除 </el-button>
          </template>
        </el-popconfirm>
      </template>
    </BasicTable>
    <BasicDialog
      :title="dialogTitle"
      :cancelButtonText="cancelButtonText"
      :visible="dialogVisible"
      @update:visible="dialogClosed"
      @reset="dialogReset"
      @confirm="dialogConfirm"
    >
      <template #default>
        <el-form ref="ruleFormRef" :model="dialogForm" label-width="140px" status-icon>
          <el-form-item label="支出">
            <el-input v-model="dialogForm.value" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="dialogForm.remark" />
          </el-form-item>
        </el-form>
      </template>
    </BasicDialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import BasicTable from '@/components/table/Index.vue'
import BasicDialog from '@/components/dialog/Index.vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
const emit = defineEmits(['pay-total'])
const tableData = ref([])
const columns = ref([
  { prop: 'value', label: '支出' },
  { prop: 'remark', label: '备注' }
])
let currentRow = {}
const currentRowChange = (rowData) => {
  currentRow = rowData
}
onMounted(() => {
  getTableData()
})

const getTableData = () => {
  tableData.value = JSON.parse(localStorage.getItem('payData')) || []
}
const savaTableData = () => {
  // // 将字符串日期转换为 Date 对象
  // tableData.value.forEach((item) => {
  //   item.time2 = new Date(item.time)
  // })

  // // 按照日期升序排列
  // tableData.value.sort((a, b) => b.time2 - a.time2)
  localStorage.setItem('payData', JSON.stringify(tableData.value))
}

const dialogForm = ref({
  value: '',
  remark: ''
})
const ruleFormRef = ref(null)
const dialogVisible = ref(false)

let dialogType = ''
let dialogTitle = ''
let cancelButtonText = ''

// type为add新增/edit编辑
const openDialog = (type, rowData) => {
  dialogType = type
  if (type === 'edit') {
    dialogTitle = '编辑'
    cancelButtonText = '获取'
    dialogForm.value = { ...rowData }
  } else {
    dialogTitle = '新增'
    cancelButtonText = '清空'
    Object.keys(dialogForm.value).map((key) => {
      dialogForm.value[key] = ''
    })
  }
  dialogVisible.value = true
}
// 表单重置
const dialogReset = () => {
  if (dialogType == 'add') {
    Object.keys(dialogForm.value).map((key) => {
      dialogForm.value[key] = ''
    })
  } else {
    dialogForm.value = { ...currentRow }
  }
}
// 表单确定
const dialogConfirm = async () => {
  const data = {
    ...dialogForm.value
  }
  if (dialogType == 'add') {
    data.id = new Date().getTime()
    tableData.value.push(data)
  } else {
    const index = tableData.value.findIndex((bill) => bill.id === data.id)
    if (index !== -1) {
      tableData.value[index] = data
    }
    console.log(data, 'index')
  }
  dialogVisible.value = false
  savaTableData()
}

const dialogClosed = () => {
  dialogVisible.value = false
  resetForm(ruleFormRef.value)
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

const deleteBill = (row) => {
  const index = tableData.value.findIndex((bill) => bill.id === row.id)
  if (index !== -1) {
    tableData.value.splice(index, 1)
    savaTableData()
  }
}

watch([() => dialogForm.value.num, () => dialogForm.value.unitPrice], ([num, unitPrice]) => {
  // 如果num和unitPrice都存在且不为空字符串，则进行计算
  if (num && unitPrice) {
    // 这里可以根据需要进行计算，例如将结果赋给dialogForm.value
    dialogForm.value.value = parseFloat(num) * parseFloat(unitPrice)
  }
})

watch(
  () => tableData.value,
  () => {
    let num = 0
    tableData.value.forEach((item) => {
      if (item.value) {
        num += parseFloat(item.value)
      }
    })
    emit('pay-total', num)
  }
)
</script>

<style lang="scss" scoped></style>
